package com.shuyu.web.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuyu.common.core.controller.BaseController;
import com.shuyu.common.core.page.TableDataInfo;
import com.shuyu.domain.ActivityProduct;
import com.shuyu.domain.Product;
import com.shuyu.service.ActivityProductService;
import com.shuyu.service.ProductService;
import com.shuyu.vo.PointMailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/mall")
@Api(tags = "前端-商城相关")
public class MallController extends BaseController {
    @Resource
    private ProductService productService;
    @Resource
    private ActivityProductService activityProductService;

    @GetMapping
    @ApiOperation("获取商城列表")
    public TableDataInfo<List<Product>> mail() {
        startPage();
        List<Product> list = productService.list(new LambdaUpdateWrapper<Product>()
                .eq(Product::getStatus, 0).eq(Product::getType,3).eq(Product::getDelFlag,0)
                .orderByDesc(Product::getCreateTime));
        Map<Integer, Product> productMap = list.stream().collect(Collectors.toMap(Product::getId, Function.identity()));
        //获取是否参加活动
        List<Integer> productIdList = list.stream().map(Product::getId).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(productIdList)){
            List<ActivityProduct> activityProductList = activityProductService.list(new LambdaQueryWrapper<ActivityProduct>()
                    .in(ActivityProduct::getProductId,productIdList).eq(ActivityProduct::getActivityType,3)
                    .le(ActivityProduct::getEndTime,new Date()).ge(ActivityProduct::getStartTime,new Date()));

            for (ActivityProduct activityProduct : activityProductList) {
                if(activityProduct.getDiscountStatus()==1){
                    Product product = productMap.get(activityProduct.getProductId());
                    double activityPrice = product.getPrice()*activityProduct.getDiscount()/100;
                    product.setActivityPrice(activityPrice);
                }
            }
        }

        return getDataTable(list);
    }
    @GetMapping("/pointMail")
    @ApiOperation("获取积分商城列表")
    public TableDataInfo<List<PointMailVo>> pointMail() {
        startPage();
        List<PointMailVo> list= activityProductService.getPointMail();
        return getDataTable(list);
    }
}
